package fr.sedoo.metadata.server.service.dao;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.geotoolkit.factory.FactoryRegistry;
import org.geotoolkit.metadata.iso.citation.Citations;
import org.geotoolkit.referencing.CRS;
import org.geotoolkit.util.logging.Logging;
import org.opengis.referencing.crs.CoordinateReferenceSystem;

import fr.sedoo.metadata.shared.domain.entity.EpsgCode;

public class EpsgDAOGeotoolkitImpl implements EpsgDAO {

	private static ArrayList<EpsgCode> cache = null;

	public EpsgDAOGeotoolkitImpl() throws Exception {
		Logger logger = Logging.getLogger(FactoryRegistry.class);
		logger.setLevel(Level.OFF);
		init();
	}

	@Override
	public ArrayList<EpsgCode> findAll() throws Exception {
		return cache;
	}

	private static void init() throws Exception {
		cache = new ArrayList<EpsgCode>(4000);

		Set<String> supportedCodes = CRS.getSupportedCodes(Citations.EPSG.getName());
		Iterator<String> iterator = supportedCodes.iterator();
		while (iterator.hasNext()) {
			String code = iterator.next();
			try {
				CoordinateReferenceSystem decode = CRS.decode(Citations.EPSG.getName() + ":" + code);
				EpsgCode epsgCode = new EpsgCode();
				epsgCode.setCode(new Integer(code));
				epsgCode.setLabel(decode.getName().toString());
				cache.add(epsgCode);
			} catch (Throwable e) {
				continue;
			}
		}

		Collections.sort(cache);
	}

}
